import React, { Component } from "react";
import { Text, View, StyleSheet, TouchableOpacity, Image, ActivityIndicator, DeviceEventEmitter, Platform, SectionList, Dimensions } from 'react-native';
import AndroidModule from "../../utils/AndroidConnent";
import Constant from '../../utils/Constant'//全局变量
import { getImgUrl, getCarRegisterDate, getMileFormat } from '../../utils/ComFunction';
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import { CarSaleStatus } from '../../utils/Enum'
import StatusBarSelf from "../../components/StatusBarSelf";
import Swiper from 'react-native-swiper'
import PriceRangeModal from "../car/stock/PriceRangeModal";
import SortDropdown from "../car/stock/SortDropdown";
import RegionPickerView from '../../components/Tool/RegionPickerView';
import AsyncImage from "../../components/image/AsyncImage";
import CarListShareBox from '../car/stock/CarListShareBox'
import BottomShareDialog, { SharePlatForm } from "../common/BottomShareDialog";
import { shareWebToSession, shareWebToTimeline } from '../../utils/WeChatUtils'
import base64 from 'react-native-base64';
import NoData from "../../utils/NoData";


const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;

let navigation

export default class JoinCarListPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            selectedIndex: 0,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            pageNo: 1,
            pageSize: 20,
            isRefresh: false,

            isShowSortDrop: false,
            sortShowText: '排序',
            orderColumns: [],

            keyword: '',
            filterShowList: [],
            isReported: 0,
            mileageMin: 0,
            mileageMax: 10,
            registerDateBegin: 0,
            registerDateEnd: 8,
            carColor: '',
            carRank: '',
            gearboxType: 0,
            gearboxTypeTitle: '',
            emissionStd: 0,
            emissionStdTitle: '',
            energyType: 0,
            energyTypeTitle: '',

            brand: 0,
            series: 0,

            isPriceModalVisible: false,
            markedPriceMin: 0,
            markedPriceMax: 0,
            showCityPicker: false,
            carProvince: 0,
            carCity: 0,
            isShowShareBottom: false,
            searchParams: {},
            carTotal: 0,

            bannerArray: [],
            carSections: [{
                'key': 'baseInfo',
                'data': [
                    { "cell": "picInfo" }, //轮播图信息
                ]
            }, {
                'key': 'contentInfo',
                'data': []
            }],

            // 新加的多选条件
            carColorList: [],
            carColorListPr: [],
            carRankList: [],
            carRankListPr: [],
            gearboxTypeList: [],
            gearboxTypeListPr: [],
            emissionStdList: [],
            emissionStdListPr: [],
            energyTypeList: [],
            energyTypeListPr: [],
        }
    }

    componentWillUnmount() {
        if (this.commonEvent) {
            this.commonEvent.remove();
        }
        if (this.selectBrandResult) {
            this.selectBrandResult.remove();
        }
        if(this.backHome){
            this.backHome.remove();
        }
    }

    componentDidMount() {
        this.commonEvent = DeviceEventEmitter.addListener('commonEvent', (data) => {
            console.log('data ==== ', data)
            if (data.type == 'search' && data.fromPage == 'JoinCarListPage') {
                let keywordObj = {
                    title: data.keyword,
                    key: 'keyword',
                    value: data.keyword
                }
                this.addFilter(keywordObj)
                this.setState({
                    keyword: data.keyword,
                }, function () {
                    this.refreshCarList()
                })
            } else if (data.type == 'moreFilter' && data.fromPage == 'JoinCarListPage') {
                this.addAllFilterShow(data)
                this.refreshCarList()
            }
        })

        this.selectBrandResult = DeviceEventEmitter.addListener('selectBrandResult', (result) => {
            if (result && result.from == 'JoinCarListPage') {
                this.formatBrand(result)
            }
        })

        this.backHome = DeviceEventEmitter.addListener('backHome', (result) => {
            if (result && result.index == 1) {
                navigation.navigate('WorkCenterPage')
            }
        })

        this.focusListener = this.props.navigation.addListener('focus', () => {

            DeviceEventEmitter.emit('homeListener', {isInHome:false,index:1});
        });

        this.setState({
            isRefresh: true
        }, () => {
            this.getBannerPic()
            this.getCarList()
        })
    }

    getBannerPic() {
        let params = {
            enableStatus: 1,
            parentType: 14
        }
        HttpUtils.postRequest(HttpUrls.queryPics, params)
            .then((result) => {
                if (result.code == 0) {
                    this.setState({
                        bannerArray: result.data.resultList
                    })
                }
            })
            .catch((error) => {

            });
    }

    render() {
        navigation = this.props.navigation
        return (
            <View style={styles.container}>
                <StatusBarSelf color='#ffffff'></StatusBarSelf>
                {this.renderNavigationBar()}

                <SectionList
                    // ref={(sectionList) => { this.sectionList = sectionList }}
                    renderSectionHeader={this.renderSectionHeader}
                    stickySectionHeadersEnabled={true}
                    style={{ flex: 1 }}
                    sections={this.state.carSections}
                    renderItem={this.renderItem.bind(this)}
                    onEndReachedThreshold={0.1}
                    onEndReached={() => this.reachedEnd()}
                    onRefresh={this.refreshData}
                    ListFooterComponent={() => this.renderFooter()}
                    showsHorizontalScrollIndicator={false}
                    keyExtractor={this._extraUniqueKey}
                    refreshing={this.state.isRefresh}
                />

                <SortDropdown
                    onSelect={(result) => {
                        console.log(result);
                        this.setState({
                            isShowSortDrop: false,
                            orderColumns: result.value,
                            sortShowText: result.title == '默认排序' ? '排序' : result.title
                        }, function () {
                            this.refreshCarList()
                        })
                    }}
                    visible={this.state.isShowSortDrop}
                    onClose={() => {
                        this.setState({
                            isShowSortDrop: false
                        })
                    }}>
                </SortDropdown>

                <PriceRangeModal
                    visible={this.state.isPriceModalVisible}
                    onClose={() => this.setIsPriceModalVisible(false)}
                    onConfirm={(min, max, priceTitle) => this.setPriceRange(min, max, priceTitle)}
                    markedPriceMin={this.state.markedPriceMin}
                    markedPriceMax={this.state.markedPriceMax}>
                </PriceRangeModal>

                <RegionPickerView
                    show={this.state.showCityPicker}
                    mode={'pc'}
                    hide={() => {
                        this.setState({
                            showCityPicker: false
                        })
                    }}
                    selectArea={(item) => {
                        let address = item.provinceName + item.cityName
                        let addressObj = {
                            title: address,
                            key: 'address',
                            value: address
                        }
                        this.addFilter(addressObj)

                        this.setState({
                            showCityPicker: false,
                            carProvince: item.provinceId,
                            carCity: item.cityId
                        }, function () {
                            this.refreshCarList()
                        })
                    }}
                />

                {this.state.isShowShareBottom ?
                    <BottomShareDialog
                        isRoot={true}
                        sharePlatForms={
                            [
                                SharePlatForm.SharePlatFormWeChatSession,
                                SharePlatForm.SharePlatFormWeChatTimeline
                            ]
                        }
                        visible={this.state.isShowShareBottom}
                        shareResult={(platform) => {
                            if (platform == SharePlatForm.SharePlatFormWeChatSession || platform == SharePlatForm.SharePlatFormWeChatTimeline) {
                                this.shareWebToWx(platform)
                            }
                        }}
                        onClose={() => {
                            this.setState({
                                isShowShareBottom: false
                            })
                        }}>

                    </BottomShareDialog>
                    :
                    null
                }



            </View>
        );
    }

    renderNavigationBar() {
        return (
            <View
                style={[styles.topContain, { height: isIos ? 44 : 49 }]}>

                <TouchableOpacity style={{height:"100%", justifyContent:"center"}}
                                  onPress={() => {
                                      if (!navigation.canGoBack()) {
                                      }
                                      else {
                                          navigation.goBack();
                                      }

                                  }}
                >
                    {!(!navigation.canGoBack()) && (<Image source={require('source/image/comm/back.png')} style={{ width: 18, height: 16, marginLeft:15 }} />)}
                </TouchableOpacity>

                <TouchableOpacity
                    activeOpacity={0.8}
                    style={styles.searchContain}
                    onPress={() => {
                        navigation.navigate('SearchPage', { fromPage: 'JoinCarListPage' })
                    }}
                >
                    <Text style={styles.searchInput}>{'请输入车辆名称或库存号'}</Text>
                    <Image style={styles.searchImg} source={require('source/image/comm/icon_sc_search.png')}></Image>
                </TouchableOpacity>

               <View style={styles.iconContain}></View>

            </View>
        )
    }

    renderSectionHeader = (info) => {
        console.log(info, 'info')
        let section = info.section.key;
        if (section === 'contentInfo') {
            return (
                <View style={{ flexDirection: 'column', width: '100%' }}>

                    {this.renderFilterView()}
                    {
                        this.state.filterShowList ?
                            this.renderFilterShow()
                            :
                            null
                    }
                </View>

            )
        }
    }

    renderFilterView() {
        return (
            <View style={styles.filterBox}>
                <TouchableOpacity
                    style={styles.filterItem}
                    onPress={() => {
                        this.setState({
                            showCityPicker: true
                        })
                    }}>
                    <Text style={styles.filterText}>城市</Text>
                    <Image style={styles.filterImg} source={require('source/image/comm/down_small_gray.png')}></Image>
                </TouchableOpacity>
                <TouchableOpacity
                    style={styles.filterItem}
                    activeOpacity={0.8}
                    onPress={() => {
                        let params = { selectLevel: 2, from: 'JoinCarListPage' }
                        AndroidModule.selectBrand(params, (error, result) => {
                            console.log('result = ', result)
                            this.formatBrand(result)
                        })
                    }}
                >
                    <Text style={styles.filterText}>{'品牌'}</Text>
                    <Image source={require('source/image/comm/down_small_gray.png')} />
                </TouchableOpacity>
                <TouchableOpacity
                    style={styles.filterItem}
                    activeOpacity={0.8}
                    onPress={() => {
                        this.setState({
                            isPriceModalVisible: true
                        })
                    }}
                >
                    <Text style={styles.filterText}>{'价格'}</Text>
                    <Image source={require('source/image/comm/down_small_gray.png')} />
                </TouchableOpacity>
                <TouchableOpacity
                    style={styles.filterItem}
                    activeOpacity={0.8}
                    onPress={() => {
                        this.setState({
                            isShowSortDrop: true
                        })
                    }}
                >
                    <Text style={this.state.orderColumns.length > 0 ? styles.filterSelText : styles.filterText} numberOfLines={1}>{this.state.sortShowText}</Text>
                    <Image source={this.state.orderColumns.length > 0 ? require('source/image/comm/up_small_yeoolow.png') : require('source/image/comm/down_small_gray.png')} />
                </TouchableOpacity>
                <TouchableOpacity
                    style={styles.filterItem}
                    activeOpacity={0.8}
                    onPress={() => {
                        navigation.navigate('MoreFilterPage', {
                            fromPage: 'JoinCarListPage',
                            isReported: this.state.isReported,
                            mileageMin: this.state.mileageMin,
                            mileageMax: this.state.mileageMax,
                            registerDateBegin: this.state.registerDateBegin,
                            registerDateEnd: this.state.registerDateEnd,

                            carColorList: this.state.carColorList,
                            carRankList: this.state.carRankList,
                            gearboxTypeList: this.state.gearboxTypeList,
                            emissionStdList: this.state.emissionStdList,
                            energyTypeList: this.state.energyTypeList,
                        })
                    }}
                >
                    <Text style={styles.filterText}>{'更多'}</Text>
                    <Image source={require('source/image/comm/down_small_gray.png')} />
                </TouchableOpacity>
            </View>
        )
    }

    renderFilterShow() {
        return (
            <View style={styles.filterShowContain}>
                {this.state.filterShowList.map((item, index) => {
                    if (item.key == 'clear') {
                        return (
                            <TouchableOpacity
                                key={index}
                                style={styles.filterShowItem}
                                onPress={() => {
                                    this.clearFilterShow()

                                }}>
                                <Image style={styles.filterShowClearImg} source={require('source/image/comm/btn_clear_history.png')}></Image>
                                <Text style={styles.filterShowText}>清空</Text>

                            </TouchableOpacity>
                        )
                    } else {
                        return (
                            <TouchableOpacity
                                key={index}
                                style={styles.filterShowItem}
                                onPress={() => {
                                    this.removeFilterShow(item, index)
                                }}>
                                <Text style={styles.filterShowText}>{item.title}</Text>
                                <Image style={styles.filterShowCloseImg} source={require('source/image/comm/icon_close.png')}></Image>
                            </TouchableOpacity>
                        )
                    }

                })
                }
            </View>
        )
    }

    formatBrand(result) {
        if (result.brandId == 0 || !result || Object.keys(result).length == 0) {
            this.removeBrand()
        } else {
            let brandObj = {
                title: result.brandName,
                key: 'brand',
                value: result.brandId
            }
            this.addFilter(brandObj)

            if (result.seriesId == 0 || !result.seriesId) {
                this.removeSeriesBrand()
            } else {
                let seriesObj = {
                    title: result.seriesName,
                    key: 'series',
                    value: result.seriesId
                }
                this.addFilter(seriesObj)
            }

        }
        this.setState({
            brand: result.brandId,
            series: result.seriesId,
        }, function () {
            this.refreshCarList()
        })
    }

    addFilter(filterModel) {
        let filterShowList = this.state.filterShowList
        let clear = {
            key: 'clear',
        }
        if (filterShowList.length == 0) {
            filterShowList.push(filterModel)
            filterShowList.push(clear)

        } else {
            let isExist = false
            for (let i = 0; i < filterShowList.length; i++) {
                if (filterShowList[i].key == filterModel.key) {
                    isExist = true
                    filterShowList[i] = filterModel
                }
            }

            if (isExist) {

            } else {
                filterShowList.splice(filterShowList.length - 2, 0, filterModel);
                // filterShowList.push(filterModel)
            }
        }

        this.setState({
            filterShowList: filterShowList
        })
    }

    removeFilterShow(item, index) {
        let filterShowList = this.state.filterShowList
        let temp = []
        for (let i = 0; i < filterShowList.length; i++) {
            if (i != index) {
                temp.push(filterShowList[i])
            }
        }

        if (item.key == 'keyword') {
            this.setState({
                keyword: ''
            })
        }
        else if (item.key == 'isReported') {
            this.setState({
                isReported: 0
            })
        }
        else if (item.key == 'mileage') {
            this.setState({
                mileageMin: 0,
                mileageMax: 10
            })
        }
        else if (item.key == 'carAge') {
            this.setState({
                registerDateBegin: 0,
                registerDateEnd: 8
            })
        }
        else if (item.key == 'brand') {
            this.setState({
                brand: 0
            })
        } else if (item.key == 'series') {
            this.setState({
                series: 0
            })
        } else if (item.key == 'price') {
            this.setState({
                markedPriceMin: 0,
                markedPriceMax: 0
            })
        } else if (item.key == 'date') {
            this.setState({
                tradeDateBegin: '',
                tradeDateEnd: '',
                tradeDateText: ''
            })
        } else if (item.key == 'sellerUserId') {
            this.setState({
                sellerUserId: ''
            })
        } else if (item.key == 'address') {
            this.setState({
                carProvince: 0,
                carCity: 0
            })
        }else if(item.key == 'carColorList'){
            this.state.carColorList.map((color, index)=>{
                if(item.value == color){
                    this.state.carColorList.splice(index,1)
                }
            })
        }else if(item.key == 'carRankList'){
            this.state.carRankList.map((Rank, index)=>{
                if(item.value == Rank){
                    this.state.carRankList.splice(index,1)
                }
            })
        }else if(item.key == 'gearboxTypeList'){
            this.state.gearboxTypeList.map((gearbox, index)=>{
                if(item.value == gearbox){
                    this.state.gearboxTypeList.splice(index,1)
                }
            })
        }else if(item.key == 'emissionStdList'){
            this.state.emissionStdList.map((emission, index)=>{
                if(item.value == emission){
                    this.state.emissionStdList.splice(index,1)
                }
            })
        }else if(item.key == 'energyTypeList'){
            this.state.energyTypeList.map((energy, index)=>{
                if(item.value == energy){
                    this.state.energyTypeList.splice(index,1)
                }
            })
        }

        if (temp.length == 1) {
            temp = []
        }

        this.setState({
            filterShowList: temp
        }, function () {
            this.refreshCarList()
        })
    }

    clearFilterShow() {
        this.setState({
            keyword: '',
            filterShowList: [],
            isReported: 0,
            mileageMin: 0,
            mileageMax: 10,
            markedPriceMin: 0,
            markedPriceMax: 0,
            registerDateBegin: 0,
            registerDateEnd: 8,
            carColor: '',
            carRank: '',
            gearboxType: 0,
            emissionStd: 0,
            energyType: 0,
            brand: 0,
            series: 0,
            carProvince: 0,
            carCity: 0,
            // 多选
            carColorList: [],
            carRankList: [],
            gearboxTypeList: [],
            emissionStdList: [],
            energyTypeList: [],
        }, function () {
            this.refreshCarList()
        })
    }

    removeBrand() {
        let temp = []
        for (let i = 0; i < this.state.filterShowList.length; i++) {
            if (this.state.filterShowList[i].key != 'brand' && this.state.filterShowList[i].key != 'series') {
                temp.push(this.state.filterShowList[i])

            }
        }

        if (temp.length == 1) {
            temp = []
        }

        this.setState({
            filterShowList: temp
        })
    }

    removeSeriesBrand() {
        let temp = []
        for (let i = 0; i < this.state.filterShowList.length; i++) {
            if (this.state.filterShowList[i].key != 'series') {
                temp.push(this.state.filterShowList[i])
            }
        }

        if (temp.length == 1) {
            temp = []
        }

        this.setState({
            filterShowList: temp
        })
    }

    renderBanner() {
        return <View style={styles.bannerContain}>
            <Swiper
                style={styles.wrapper}
                removeClippedSubviews={false}
                showsButtons={false}
                loop={true}
                horizontal={true}
                autoplay={true}
                autoplayTimeout={3}
                onIndexChanged={(index) => {

                }}
                dot={<View style={{
                    backgroundColor: '#DCDCDC',
                    width: 6,
                    height: 6,
                    borderRadius: 3,
                    marginRight: 5,
                    marginBottom: -30
                }} />}
                activeDot={<View style={{
                    backgroundColor: '#F99802',
                    width: 6,
                    height: 6,
                    borderRadius: 3,
                    marginRight: 5,
                    marginBottom: -30
                }} />}

            >
                {this.state.bannerArray.map((item, index) => {
                    return (
                        <TouchableOpacity
                            key={index + ''}
                            style={{ height: '100%' }}
                            activeOpacity={1.0}
                            onPress={() => {

                            }}>
                            <Image style={styles.bannerImg} source={{ uri: getImgUrl(item.picUrl) }}></Image>
                        </TouchableOpacity>
                    );
                })}

            </Swiper>
        </View>;
    }

    reachedEnd() {
        if (this.state.carSections[1].data.length == 0) {
            return null;
        }

        if (this.state.showFoot != 0) {
            return null;
        }
        let pageNo = this.state.pageNo + 1
        this.setState({
            showFoot: 2,
            pageNo: pageNo
        }, function () {
            this.getCarList()
        });

    }

    renderFooter() {
        if (this.state.carSections[1].data.length == 0) {
            return (
                null
            )
        }

        if (this.state.showFoot == 2) {
            return (
                <View style={{ padding: 10, backgroundColor: '#ffffff', display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
                    <ActivityIndicator size="small" color="#333333" />
                    <Text style={{ marginLeft: 10, fontSize: 15, color: '#333333' }}>加载中...</Text>
                </View>
            )
        } else {
            return null;
        }
    }

    renderItem(data) {
        console.log(data, 'ddddd')
        if (data.item.cell == 'picInfo') {
            return (
                <View>
                    {
                        this.state.bannerArray.length > 0 ?
                            this.renderBanner()
                            :
                            null
                    }
                </View>
            )
        } else {
            if (data.item.emptyCell) {
                return (
                    <View style={{ width: '100%', height: 260 }}>
                        <NoData Desc="暂无数据" style={{ marginTop: gREM(40) }} />
                    </View>
                )
            } else {
                return (
                    <View style={{ width: '100%', paddingHorizontal: 15 }}>
                        {this.renderCarItem(data.item)}
                    </View>
                )
            }
        }
    }

    renderCarItem(item) {
        let items = item.items
        let leftItem = items[0]
        let rightItem = items.length > 1 ? items[1] : {}
        return (
            <View style={styles.carBg}>
                <TouchableOpacity
                    activeOpacity={0.8}
                    style={[styles.carBox, { marginRight: 12 }]}
                    onPress={() => {
                        navigation.navigate('CarDetailPage', {
                            carId: leftItem.carId,
                            saleStatus: leftItem.saleStatus,
                            merchantId: leftItem.merchantId,
                            isJoinCar: 1,
                            carDetailCallBack: () => {
                                this.refreshCarList()
                            }
                        })
                    }}
                >
                    <View style={styles.labelBox}>
                        {
                            leftItem.detectionStatus == 3 ?
                                <Image style={{ width: 59, height: 18, marginRight: 4 }} source={require('source/image/detection_auth.png')} />
                                :
                                null
                        }

                        {
                            leftItem.isReported == 1 ?
                                <View style={[styles.labelItemBox, { backgroundColor: '#FFF5E6' }]}>
                                    <Text style={[styles.labelText, { color: '#F99802' }]}>有维保</Text>
                                </View>
                                :
                                null
                        }

                        {
                            leftItem.saleStatus == CarSaleStatus.CarSaleStatusReserved ?
                                <View style={[styles.labelItemBox, { backgroundColor: '#F1FAED' }]}>
                                    <Text style={[styles.labelText, { color: '#6ECC49' }]}>已预订</Text>
                                </View>
                                :
                                null
                        }
                    </View>

                    <AsyncImage style={styles.carImg} source={{ uri: getImgUrl(leftItem.mainPic) }} defaultSource={require('source/image/car/car_default_list_left.png')} />
                    <View style={styles.bottomBox}>
                        <Text style={styles.brandText}>
                            {
                                leftItem.carType == 1 ?
                                    <View style={styles.newCarBox}>
                                        <Text style={styles.newCarText}>新车</Text>
                                    </View>
                                    :
                                    null
                            }

                            {(leftItem.carType == 1 ? ' ' : '') + leftItem.seriesName + ' ' + leftItem.speciesName}
                        </Text>

                        <Text style={styles.infoText}>{this.getSubCarInfo(leftItem)}</Text>

                        <Text style={styles.priceText}>{(leftItem.markedPrice ? (leftItem.markedPrice / 10000).toFixed(2) + '万元' : '未定价')}</Text>

                        {
                            leftItem.merchantAbbreviation ?
                                <View style={styles.cityBox}>
                                    <Image source={require('source/image/location_gray.png')} />
                                    <Text style={styles.loationText}>{leftItem.merchantAbbreviation}</Text>
                                </View>
                                :
                                null
                        }
                    </View>
                </TouchableOpacity>
                {
                    Object.keys(rightItem).length > 0 ?
                        <TouchableOpacity
                            activeOpacity={0.8}
                            style={styles.carBox}
                            onPress={() => {
                                navigation.navigate('CarDetailPage', {
                                    carId: rightItem.carId,
                                    saleStatus: rightItem.saleStatus,
                                    merchantId: rightItem.merchantId,
                                    isJoinCar: 1,
                                    carDetailCallBack: () => {
                                        this.refreshCarList()
                                    }
                                })
                            }}
                        >
                            <View style={styles.labelBox}>
                                {
                                    rightItem.detectionStatus == 3 ?
                                        <Image style={{ width: 59, height: 18, marginRight: 4 }} source={require('source/image/detection_auth.png')} />
                                        :
                                        null
                                }

                                {
                                    rightItem.isReported == 1 ?
                                        <View style={[styles.labelItemBox, { backgroundColor: '#FFF5E6' }]}>
                                            <Text style={[styles.labelText, { color: '#F99802' }]}>有维保</Text>
                                        </View>
                                        :
                                        null
                                }

                                {
                                    rightItem.saleStatus == CarSaleStatus.CarSaleStatusReserved ?
                                        <View style={[styles.labelItemBox, { backgroundColor: '#F1FAED' }]}>
                                            <Text style={[styles.labelText, { color: '#6ECC49' }]}>已预订</Text>
                                        </View>
                                        :
                                        null
                                }
                            </View>
                            <AsyncImage style={styles.carImg} source={{ uri: getImgUrl(rightItem.mainPic) }} defaultSource={require('source/image/car/car_default_list_left.png')} />
                            <View style={styles.bottomBox}>
                                <Text style={styles.brandText} numberOfLines={2}>
                                    {
                                        rightItem.carType == 1 ?
                                            <View style={styles.newCarBox}>
                                                <Text style={styles.newCarText}>新车</Text>
                                            </View>
                                            :
                                            null
                                    }

                                    {(rightItem.carType == 1 ? ' ' : '') + rightItem.seriesName + ' ' + rightItem.speciesName}
                                </Text>

                                <Text style={styles.infoText}>{this.getSubCarInfo(rightItem)}</Text>

                                <Text style={styles.priceText}>{(rightItem.markedPrice ? (rightItem.markedPrice / 10000).toFixed(2) + '万元' : '未定价')}</Text>

                                {
                                    rightItem.merchantAbbreviation ?
                                        <View style={styles.cityBox}>
                                            <Image source={require('source/image/location_gray.png')} />
                                            <Text style={styles.loationText}>{rightItem.merchantAbbreviation}</Text>
                                        </View>
                                        :
                                        null
                                }
                            </View>
                        </TouchableOpacity>
                        :
                        <View style={[styles.carBox, { backgroundColor: 'rgba(0,0,0,0)' }]} />
                }

            </View>
        )
    }

    getSubCarInfo(item) {
        let string = ''
        if (item.carType == 1) {
            if (item.guidePrice) {
                string = '指导价' + (item.guidePrice / 10000).toFixed(2) + '万元'
            }
            if (string.length > 0 && item.cityName) {
                string = string + ' | ' + item.cityName
            }
            return string
        } else {
            if (item.registerDate) {
                string = getCarRegisterDate(item.registerDate)
            }
            if (string.length > 0 && item.mileage) {
                string = string + ' | ' + getMileFormat(item.mileage)
            }
            if (string.length > 0 && item.cityName) {
                string = string + ' | ' + item.cityName
            }
            return string
        }

    }

    refreshCarList() {
        this.setState({
            pageNo: 1,
            carSections: [{
                'key': 'baseInfo',
                'data': [
                    { "cell": "picInfo" },
                ]
            }, {
                'key': 'contentInfo',
                'data': []
            }]
        }, function () {
            this.getCarList()
        })
    }

    refreshData = () => {
        this.setState({
            carSections: [{
                'key': 'baseInfo',
                'data': [
                    { "cell": "picInfo" },
                ]
            }, {
                'key': 'contentInfo',
                'data': []
            }],
            isRefresh: true,
            pageNo: 1
        }, function () {
            this.getCarList();
        })

    }

    getCarList() {
        let params = {
            pageNo: this.state.pageNo,
            pageSize: this.state.pageSize,
            searchChannel: "franchisee_all_car_query_car",
            // memberClasses: [40],
            // carType: this.state.selectedIndex == 0 ? 1 : 2,
        }

        if (this.state.isFranchisee) {
            params['joinQuotationCenter'] = 1
        }

        if (this.state.brand != 0) {
            params['brand'] = this.state.brand
        }

        if (this.state.series != 0) {
            params['series'] = this.state.series
        }

        if (this.state.markedPriceMin != 0) {
            params['markedPriceMin'] = this.state.markedPriceMin * 10000
        }

        if (this.state.markedPriceMax != 0) {
            params['markedPriceMax'] = this.state.markedPriceMax * 10000
        }

        if (this.state.orderColumns.length > 0) {
            params['orderColumns'] = this.state.orderColumns
        }

        if (this.state.isReported != 0) {
            params['isReported'] = this.state.isReported
        }

        if (this.state.mileageMin != 0) {
            params['mileageMin'] = this.state.mileageMin * 10000
        }
        if (this.state.mileageMax != 10) {
            params['mileageMax'] = this.state.mileageMax * 10000
        }

        if (this.state.carColor != '') {
            params['carColor'] = this.state.carColor
        }

        if (this.state.keyword != '') {
            params['carName'] = this.state.keyword
        }

        // 外观颜色
        if(this.state.carColorList && this.state.carColorList.length > 0){
            params['carColorList'] = this.state.carColorList
        }
        // 车型级别
        if(this.state.carRankList && this.state.carRankList.length > 0){
            params['carRankList'] = this.state.carRankList
        }
        // 变速箱
        if(this.state.gearboxTypeList && this.state.gearboxTypeList.length > 0){
            params['gearboxTypeList'] = this.state.gearboxTypeList
        }
        // 排放标准
        if(this.state.emissionStdList && this.state.emissionStdList.length > 0){
            params['emissionStdList'] = this.state.emissionStdList
        }
        // 能源类型
        if(this.state.energyTypeList && this.state.energyTypeList.length > 0){
            params['energyTypeList'] = this.state.energyTypeList
        }

        console.log('params = ', params);

        let nowDate = new Date()
        let nowYear = nowDate.getFullYear()
        let nowMonth = nowDate.getMonth() + 1
        let nowDay = nowDate.getDate()
        if (this.state.registerDateBegin != 0) {
            let beginDate = (nowYear - this.state.registerDateBegin) + '-' + nowMonth + '-' + nowDay
            params['registerDateEnd'] = beginDate
        }
        if (this.state.registerDateEnd != 8) {
            let endDate = (nowYear - this.state.registerDateEnd) + '-' + nowMonth + '-' + nowDay
            params['registerDateBegin'] = endDate
        }

        if (this.state.carRank != '') {
            params['carRank'] = this.state.carRank
        }

        if (this.state.gearboxType != 0) {
            params['gearboxType'] = this.state.gearboxType
        }

        if (this.state.emissionStd != 0) {
            params['emissionStd'] = this.state.emissionStd
        }

        if (this.state.energyType != 0) {
            params['energyTypeList'] = [this.state.energyType]
        }

        // if(this.state.carProvince != 0){
        //     params['carProvince'] = this.state.carProvince
        // }
        if (this.state.carCity != 0) {
            let cityCode = this.state.carCity + ''
            let cityCodeStr = cityCode.substring(0, 4)
            params['areaCode'] = cityCodeStr
        }

        this.setState({
            searchParams: params
        })

        HttpUtils.postRequest(HttpUrls.searchCars, params)
            .then((result) => {
                this.setState({
                    isRefresh: false
                })
                let resultList = result.data.resultList
                if (result.data && resultList.length > 0) {
                    let carsList = this.state.carSections[1].data
                    let tempArray = []
                    let itemArray = []
                    resultList.map((item, index) => {
                        itemArray.push(item)
                        if (index % 2 == 1) {
                            tempArray.push({ items: itemArray })
                            itemArray = []
                        } else if (index == resultList.length - 1) {
                            tempArray.push({ items: itemArray })
                            itemArray = []
                        }
                    })
                    carsList = carsList.concat(tempArray)
                    this.setState({
                        carTotal: result.data.totalSize,
                        carSections: [{
                            'key': 'baseInfo',
                            'data': [
                                { "cell": "picInfo" },
                            ]
                        }, {
                            'key': 'contentInfo',
                            'data': carsList
                        }]
                    })
                    if (result.data.resultList.length < this.state.pageSize) {
                        this.setState({
                            showFoot: 1
                        });
                    } else {
                        this.setState({
                            showFoot: 0
                        });
                    }
                } else {
                    if (this.state.pageNo == 1) {
                        this.setState({
                            carSections: [{
                                'key': 'baseInfo',
                                'data': [
                                    { "cell": "picInfo" }, //商家信息
                                ]
                            }, {
                                'key': 'contentInfo',
                                'data': [
                                    { 'emptyCell': true }
                                ]
                            }]
                        })
                    }
                    this.setState({
                        showFoot: 1
                    });
                }
            })
            .catch((error) => {

            });
    }

    setIsPriceModalVisible(visible) {
        this.setState({
            isRefresh: false,
            isPriceModalVisible: visible
        })
    }

    setPriceRange(min, max, priceTitle) {
        this.setState({
            markedPriceMin: min,
            markedPriceMax: max
        })

        let priceObj = {
            title: priceTitle,
            key: 'price',
            value: 0
        }
        this.addFilter(priceObj)

        this.refreshCarList()
    }

    addAllFilterShow(data) {

        let tempList = []
        let resultList = []
        let isReported = data.isReported

        if (isReported == 1) {
            tempList.push({
                title: '有维保',
                key: 'isReported',
                value: 1
            })
        }

        let mileShowText = data.mileShowText
        let mileageMin = data.mileageMin
        let mileageMax = data.mileageMax

        if (mileShowText === '不限') {

        } else {
            tempList.push({
                title: mileShowText,
                key: 'mileage',
                value: 0
            })
        }

        let ageShowText = data.ageShowText
        let registerDateBegin = data.registerDateBegin
        let registerDateEnd = data.registerDateEnd

        if (ageShowText === '不限') {

        } else {
            tempList.push({
                title: ageShowText,
                key: 'carAge',
                value: 0
            })
        }

        // 颜色
        if(data.carColorList && data.carColorList.length > 0){
            data.carColorList.map((item, index) => {
                let tempListItem = {
                    title: item,
                    key: 'carColorList',
                    value: item
                }
                tempList.push(tempListItem)
            })
        }
        // 车型级别
        if(data.carRankList && data.carRankList.length > 0){
            data.carRankList.map((item, index) => {
                data.carRankListPr.map( rankItem => {
                    if(rankItem.id == item){
                        let tempListItem = {
                            title: rankItem.title,
                            key: 'carRankList',
                            value: item
                        }
                        tempList.push(tempListItem)
                    }
                })
            })
        }
        // 变速箱
        if(data.gearboxTypeList && data.gearboxTypeList.length > 0){
            data.gearboxTypeList.map((item, index) => {
                data.gearboxTypeListPr.map(gItem => {
                    if(gItem.id == item){
                        let tempListItem = {
                            title: gItem.title,
                            key: 'gearboxTypeList',
                            value: item
                        }
                        tempList.push(tempListItem)
                    }
                })
            })
        }
        // 排放标准
        if(data.emissionStdList && data.emissionStdList.length > 0){
            data.emissionStdList.map((item, index) => {
                data.emissionStdListPr.map(gItem => {
                    if(gItem.id == item){
                        let tempListItem = {
                            title: gItem.title,
                            key: 'emissionStdList',
                            value: item
                        }
                        tempList.push(tempListItem)
                    }
                })
            })
        }
        // 燃油类型
        if(data.energyTypeList && data.energyTypeList.length > 0){
            data.energyTypeList.map((item, index) => {
                data.energyTypeListPr.map(rItem => {
                    if(rItem.id == item){
                        let tempListItem = {
                            title: rItem.title,
                            key: 'energyTypeList',
                            value: item
                        }
                        tempList.push(tempListItem)
                    }
                })
            })
        }

        let filterShowList = this.state.filterShowList
        if (filterShowList.length == 0) {
            resultList = tempList
        } else {
            let temp = [];
            for (let i = 0; i < filterShowList.length; i++) {
                if (filterShowList[i].key == 'keyword' || filterShowList[i].key == 'brand') {
                    temp.push(filterShowList[i])

                }
            }
            resultList = temp.concat(tempList)

        }

        resultList.push({ key: 'clear' })

        this.setState({
            isReported: isReported,
            filterShowList: resultList,
            mileageMin: mileageMin,
            mileageMax: mileageMax,
            registerDateBegin: registerDateBegin,
            registerDateEnd: registerDateEnd,

            carColorList: data.carColorList,
            carColorListPr: data.carRankListPr,
            carRankList: data.carRankList,
            carRankListPr: data.carRankListPr,
            gearboxTypeList: data.gearboxTypeList,
            gearboxTypeListPr: data.gearboxTypeListPr,
            emissionStdList: data.emissionStdList,
            emissionStdListPr: data.emissionStdListPr,
            energyTypeList: data.energyTypeList,
            energyTypeListPr: data.energyTypeListPr,
        })
    }

    shareWebToWx(platform) {
        let title = Constant.userInfo.fullname + '为您推荐了' + this.state.carTotal + '辆好车'

        let description = '【联系电话】' + '\n' + Constant.userInfo.phone

        let params = this.state.searchParams

        params['isOpen'] = 1
        params['pageNo'] = 1
        params['merchantId'] = Constant.userInfo.merchantId
        params['userId'] = Constant.userInfo.userId

        console.log('params = ',params)

        let jsonString = JSON.stringify(params)
        const base64Encoded = base64.encode(jsonString);
        let webpageUrl = Constant.webDomain + '/sharecarlist?params=' + base64Encoded
        console.log('webpageUrl = ',webpageUrl)

        let data = {
            title: title,
            description: description,
            type: 'news',
            webpageUrl: webpageUrl,
            thumbImage: getImgUrl(Constant.userInfo.face)
        }

        if (platform == 1) {
            shareWebToSession(data)
        } else {
            shareWebToTimeline(data)
        }
    }


};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f9f9f9',
        flexDirection: 'column',
    },
    topContain: {
        width: '100%',
        height: 44,
        backgroundColor: '#ffffff',
        flexDirection: 'row',
        alignItems: 'center',

    },

    iconImg: {
        width: 24,
        height: 24
    },
    iconContain: {
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center',
        width: 16,
    },
    searchContain: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
        height: 34,
        marginLeft: 16,
        backgroundColor: '#f6f6f6',
        borderRadius: 4,
        paddingHorizontal: 15,
    },
    searchInput: {
        flex: 1,
        padding: 0,
        marginLeft: 10,
        fontSize: 14,
        color: '#999',
    },
    bannerContain: {
        height: (screenW - 32) * 0.33 + 20,
        paddingVertical: 10,
        paddingHorizontal: 16,
        width: screenW,
        backgroundColor: '#fff',
    },
    wrapper: {
        borderRadius: 8,
    },
    bannerImg: {
        width: '100%',
        height: '100%',
        borderRadius: 8
    },

    tabBox: {
        width: '100%',
        height: 42,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingHorizontal: 16,
        backgroundColor: '#FFF',
    },
    tabBoxItem: {
        flex: 1,
        height: '100%',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
    },
    tabTitleTextSel: {
        color: '#F99802',
        fontSize: 18,
        fontWeight: 'bold'
    },
    tabTitleText: {
        color: '#333333',
        fontSize: 18,
        fontWeight: 'bold'
    },
    tabIndexBox: {
        width: 26,
        height: 3,
        backgroundColor: '#fff'
    },
    tabIndexSelBox: {
        position: 'absolute',
        bottom: 0,
        width: 16,
        height: 3,
        borderRadius: 1.5,
        backgroundColor: '#F99802'
    },

    filterBox: {
        width: '100%',
        height: 46,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        backgroundColor: '#FFF',
    },
    filterItem: {
        flex: 1,
        height: '100%',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
    },
    filterText: {
        fontSize: 14,
        color: '#333',
    },
    filterSelText: {
        fontSize: 14,
        color: '#F99802',
    },
    filterImg: {
        width: 20,
        height: 20,
    },

    filterShowContain: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        backgroundColor: '#fff',
        paddingHorizontal: 15
    },
    filterShowItem: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        // height: 30,
        backgroundColor: '#f6f6f6',
        borderRadius: 4,
        paddingHorizontal: 5,
        paddingVertical: 5,
        marginRight: 10,
        marginBottom: 5
    },
    filterShowText: {
        fontSize: 10,
        color: '#696969'
    },
    filterShowCloseImg: {
        width: 10,
        height: 10,
        marginLeft: 2
    },
    filterShowClearImg: {
        width: 12,
        height: 12,
        marginRight: 2,
        resizeMode: 'contain'
    },

    carBg: {
        width: '100%',
        marginTop: 10,
        flexDirection: 'row',
    },
    carBox: {
        flex: 1,
        flexDirection: 'column',
        borderRadius: 8,
        backgroundColor: '#fff'
    },
    carImg: {
        backgroundColor: '#F1F1F1',
        width: '100%',
        height: (screenW - 12 - 32) / 2 * 0.75,
        borderTopLeftRadius: 8,
        borderTopRightRadius: 8,
    },
    bottomBox: {
        padding: 8
    },
    brandText: {
        height: 36,
        color: '#333',
        fontSize: 14,
        fontWeight: '500',
        lineHeight: 18,
    },
    newCarBox: {
        paddingHorizontal: 5,
        height: 14,
        borderRadius: 2,
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: 'rgba(37, 162, 240, 0.1)',
        marginVertical: -1,
    },
    newCarText: {
        color: '#25A2F0',
        fontSize: 10,
        fontWeight: '500'
    },
    infoText: {
        marginTop: 6,
        fontSize: 10,
        color: '#999999'
    },
    priceText: {
        height: 20,
        marginTop: 6,
        fontSize: 16,
        color: '#ED542E',
        fontWeight: '500'
    },
    cityBox: {
        marginTop: 8,
        marginBottom: 2,
        width: '100%',
        height: 24,
        borderRadius: 4,
        backgroundColor: '#F4F4F4',
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 5,
    },
    loationText: {
        marginLeft: 2,
        fontSize: 10,
        color: '#666666'
    },

    labelBox: {
        zIndex: 1000,
        position: 'absolute',
        left: 6,
        top: 6,
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center'
    },
    labelItemBox: {
        marginRight: 4,
        paddingHorizontal: 6,
        height: 18,
        flexDirection: 'row',
        alignItems: 'center',
        borderRadius: 2,
        backgroundColor: '#F4F4F4'
    },
    labelText: {
        fontSize: 10,
        color: '#FF7B00'
    },
});